import { Button, Card, Checkbox, Form, Input, message, Space } from "antd";
import type { Captcha, LoginParams } from "./login.type";
import { useEffect, useState } from "react";
import { CommonApi } from "../../apis/Common";
import { useNavigate } from "react-router-dom";
import { LocalStorageManager } from "./../../cache";
import { setToken } from "./login.utils";

const localStorageManager = new LocalStorageManager();

export const Login = () => {
  // 验证码信息
  const [captcha, setCaptcha] = useState<Captcha>({});

  const navigate = useNavigate();

  const getCaptcha = async () => {
    const data = await CommonApi.getCaptcha();
    setCaptcha(data);
  };

  /**
   * 点击登录
   * @param values
   */
  const onFinish = async (values: LoginParams) => {
    try {
      const data = await CommonApi.login({
        ...values,
        captchaId: captcha.captchaId!,
      });
      message.success("登录成功");
      setToken(data);
      navigate("/");
    } catch (error) {
      getCaptcha();
    }
  };

  /**
   * 组件渲染后触发
   * 只会触发一次，可以在这里进行网络请求
   * 注意:hooks不能使用async装饰
   */
  useEffect(() => {
    getCaptcha();
  }, []);

  return (
    <div
      style={{
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        height: "100vh",
        background: "gray",
      }}
    >
      <Card style={{ width: 400 }}>
        <Form onFinish={onFinish}>
          <Form.Item
            label="Username"
            name="username"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="Password"
            name="password"
            rules={[{ required: true, message: "Please input your password!" }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item name="verifyCode" label="验证码">
            <Space>
              <Input />
              <img src={captcha.data} onClick={getCaptcha} />
            </Space>
          </Form.Item>
          {/* <Form.Item name="remember" valuePropName="checked" label={null}>
              <Checkbox>Remember me</Checkbox>
            </Form.Item> */}

          <Form.Item label={null}>
            <Button type="primary" htmlType="submit">
              Submit
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};
